<template>
  <!-- 质量异常信息表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    :width="!props.isReadonly ? '850px' : '850px'"
    draggable
    @close="closeDialog"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="110"
      v-show="!props.isReadonly"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="异常信息编号" prop="qualityExceptionCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.qualityExceptionCode"
              placeholder="请输入异常信息编号"
              :disabled="true"
              clearable
            />

            <span v-else>{{ formData.qualityExceptionCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="exceptionState">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.exceptionState"
              placeholder="请选择状态"
              clearable
              :disabled="true"
              style="width: 100%"
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('ExceptionState')"
                :key="item.value"
                :label="item.label"
                :value="Number(item.value)"
              />
            </el-select>
            <span v-else>{{ formData.exceptionState }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="图号" prop="figureNumber">
            <el-select
              style="width: 100%"
              v-if="!props.isReadonly"
              v-model="formData.materialId"
              placeholder="请选择图号"
              clearable
              @change="changeFigureNumber"
            >
              <el-option
                v-for="item in materialProcessList"
                :label="`${item.materialProcessFigure}`"
                :value="`${item.id}`"
              />
            </el-select>
            <span v-else>{{ formData.figureNumber }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品名称" prop="materialName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.materialName"
              placeholder="请选择产品名称"
              clearable
              disabled
            />

            <span v-else>{{ formData.materialName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品类目名称" prop="productionTypeName">
            <el-select
              style="width: 100%"
              v-if="!props.isReadonly"
              v-model="formData.productionTypeId"
              placeholder="请选择产品类目名称"
              clearable
              @change="changeProduction"
            >
              <el-option
                v-for="item in productionTypeList"
                :label="`${item.productionTypeName}`"
                :value="`${item.id}`"
              />
            </el-select>
            <span v-else>{{ formData.productionTypeName }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="数量" prop="exceptionQuantity">
            <el-input-number
              v-model="formData.exceptionQuantity"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="失效模式" prop="failureMode">
            <el-tree-select
              v-if="!props.isReadonly"
              placeholder="请选择失效模式"
              v-model="formData.failureMode"
              :data="failureModeList"
              node-key="id"
              :props="{
                label: 'failureModeContent',
                value: 'id',
                children: 'nodes',
              }"
              :render-after-expand="false"
              :check-strictly="true"
              style="width: 300px"
              clearable
              @node-click="handleNodeClick"
            />

            <span v-else>{{ formData.failureMode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="失效对应数量" prop="failureQuantity">
            <el-input-number
              v-model="formData.failureQuantity"
              v-if="!props.isReadonly"
              style="width: 100%"
            />
            <span v-else>{{ formData.failureQuantity }}</span>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="信息来源" prop="informationSourceId">
            <el-select
              style="width: 100%"
              v-if="!props.isReadonly"
              v-model="formData.informationSourceId"
              placeholder="请选择信息来源"
              clearable
              @change="changInformationSource"
            >
              <el-option
                v-for="item in informationSourceList"
                :label="`${item.informationSourceContent}`"
                :value="`${item.id}`"
              />
            </el-select>
            <span v-else>{{ formData.informationSourceContent }}</span>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="发生时间" prop="occurrenceTime">
            <el-date-picker
              v-if="!props.isReadonly"
              v-model="formData.occurrenceTime"
              type="date"
              placeholder="请选择发生日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
            <span v-else>{{ formData.occurrenceTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="发生地点" prop="occurrenceLocation">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.occurrenceLocation"
              placeholder="请输入发生地点"
              clearable
            />
            <span v-else>{{ formData.occurrenceLocation }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="是否内部制造" prop="isInternal">
            <el-radio-group
              v-model="formData.isInternal"
              v-if="!props.isReadonly"
              @change="changIsInternal"
            >
              <el-radio :label="1">内部生产</el-radio>
              <el-radio :label="0">外部生产</el-radio>
            </el-radio-group>
            <span v-else>{{ formData.isInternal }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formData.isInternal == 0">
          <el-form-item
            label="生产单位"
            :prop="formData.isInternal == 0 ? 'supplyId' : ''"
          >
            <el-select
              style="width: 100%"
              v-if="!props.isReadonly"
              v-model="formData.supplyId"
              placeholder="请选择生产单位"
              clearable
              @change="changSupplyList"
            >
              <el-option
                v-for="item in supplyList"
                :label="`${item.partnerCode}-${item.partnerName}`"
                :value="`${item.id}`"
              />
            </el-select>
            <span v-else>{{ formData.supplyId }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="ml-[15px]">
        <el-form-item label="附件上传">
          <CommonUploadFile
            :isRead="props.isReadonly"
            :files="formData.assetPhotos"
            @update-files="updateFormFiles"
          />
        </el-form-item>

        <!-- <image-id></image-id> -->

        <!-- <el-input
                    v-model="formData.assetPhotos"
                    style="display: none"
                  ></el-input> -->
      </el-row>
    </el-form>
    <el-descriptions
      v-show="props.isReadonly"
      class="margin-top"
      title=""
      :column="2"
      size="large"
      border
    >
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">异常信息编号</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.qualityExceptionCode || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">状态</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{
            dictionaryStore.filterDictName(
              "ExceptionState",
              Number(formData.exceptionState)
            )
          }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">产品图号</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.figureNumber || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">产品名称</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.figureNumber || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">产品类目</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.productionTypeName || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">数量</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.exceptionQuantity }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">失效模式</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.failureModeContent || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">失效对应数量</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.failureQuantity }}
        </div>
      </el-descriptions-item>
      <!-- <el-descriptions-item>
        <template #label>
          <div class="cell-item">信息来源</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.informationSourceContent || "" }}
        </div>
      </el-descriptions-item> -->
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">发生时间</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{
            formData.occurrenceTime
              ? dayjs(formData.occurrenceTime).format("YYYY-MM-DD") || ""
              : ""
          }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item :span="2">
        <template #label>
          <div class="cell-item">发生地点</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.occurrenceLocation || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">是否内部制造</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.isInternal == 1 ? "内部生产" : "外部生产" || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item v-if="formData.isInternal == 0">
        <template #label>
          <div class="cell-item">生产单位</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.supplyName }}
        </div>
      </el-descriptions-item>
    </el-descriptions>
    <div style="margin-top: 20px">
      <CommonUploadFile
        v-show="props.isReadonly"
        :isRead="props.isReadonly"
        :files="formData.assetPhotos"
        @update-files="updateFormFiles"
      />
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import dayjs from "dayjs";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMSQ8DQUALITYPROBLEMADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  qualityExceptionCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  productionTypeId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  productionTypeName: [
    // { required: true, message: "请选择产品类目名称", trigger: "change" },
  ],
  materialId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  materialCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  materialName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  figureNumber: [
    // { required: true, message: "请选择图号", trigger: "change" },
  ],
  exceptionQuantity: [
    // { required: true, message: "请输入数量", trigger: "blur" },
  ],
  failureQuantity: [
    // { required: true, message: "请输入失效对应数量", trigger: "blur" },
  ],
  failureMode: [
    // { required: true, message: "请选择失效模式", trigger: "change" },
  ],
  occurrenceTime: [
    // { required: true, message: "请选择发生时间", trigger: "change" },
  ],
  occurrenceLocation: [
    // { required: true, message: "请选择发生地点", trigger: "change" },
  ],
  informationSourceId: [
    // { required: true, message: "请选择信息来源", trigger: "change" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  informationSourceContent: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  exceptionState: [],
  isInternal: [],
  supplyId: [
    // { required: true, message: "请选择生产单位", trigger: "change" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  supplyCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  supplyName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  raiseUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  raiseUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  isClose: [],
  version: [],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  createTime: [],
  createdUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  createdUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  lastUpdateTime: [],
  lastUpdatedUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  lastUpdatedUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  enabled: [],
  deleted: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  qualityExceptionCode: "",
  productionTypeId: "",
  productionTypeName: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  figureNumber: "",

  exceptionQuantity: 0,
  failureQuantity: 0,
  failureMode: "",
  failureModeContent: "",
  occurrenceTime: "",
  occurrenceLocation: "",
  informationSourceId: "",
  informationSourceContent: "",
  exceptionState: "",
  isInternal: 1,
  supplyId: "",
  supplyCode: "",
  supplyName: "",
  raiseUserId: "",
  raiseUserName: "",
  isClose: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  assetPhotos: [],
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        qualityExceptionCode,
        productionTypeId,
        productionTypeName,
        materialId,
        materialCode,
        materialName,
        figureNumber,
        exceptionQuantity,
        failureQuantity,
        failureMode,
        failureModeContent,
        occurrenceTime,
        occurrenceLocation,
        informationSourceId,
        informationSourceContent,
        exceptionState,
        isInternal,
        supplyId,
        supplyCode,
        supplyName,
        raiseUserId,
        raiseUserName,
        isClose,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        assetPhotos,
      } = newVal;
      Object.assign(formData, {
        id,
        qualityExceptionCode,
        productionTypeId,
        productionTypeName,
        materialId,
        materialCode,
        materialName,
        figureNumber,
        exceptionQuantity,
        failureQuantity,
        failureMode,
        failureModeContent,
        occurrenceTime,
        occurrenceLocation,
        informationSourceId,
        informationSourceContent,
        exceptionState,
        isInternal,
        supplyId,
        supplyCode,
        supplyName,
        raiseUserId,
        raiseUserName,
        isClose,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        assetPhotos: assetPhotos ?? [],
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.qualityExceptionCode = "";
  formData.productionTypeId = "";
  formData.productionTypeName = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.figureNumber = "";
  formData.exceptionQuantity = 0;
  formData.failureQuantity = 0;
  formData.failureMode = "";
  formData.failureModeContent = "";
  formData.occurrenceTime = "";
  formData.occurrenceLocation = "";
  formData.informationSourceId = "";
  formData.informationSourceContent = "";
  formData.exceptionState = "";
  formData.isInternal = 1;
  formData.supplyId = "";
  formData.supplyCode = "";
  formData.supplyName = "";
  formData.raiseUserId = "";
  formData.raiseUserName = "";
  formData.isClose = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
  formData.assetPhotos = [];
}

const loading = ref(false);

/** 质量异常信息保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "转问题处理" : "转问题处理";
      await request({
        url: "/qms/q8dqualityexception/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 产品过程列表
const materialProcessList = ref([]);
async function getMaterialProcess() {
  let res = await request({
    url: "/qms/qmsmaterialprocess/getList",
    method: "post",
    data: {},
  }).finally(() => {
    loading.value = false;
  });
  materialProcessList.value = res.data;
}
const changeFigureNumber = (e) => {
  if (e) {
    materialProcessList.value.forEach((item) => {
      if (item.id == e) {
        formData.materialCode = item.materialProcessCode;
        formData.materialName = item.materialProcessName;
        formData.figureNumber = item.materialProcessFigure;
      }
    });
  } else {
    formData.materialCode = "";
    formData.materialName = "";
    formData.figureNumber = "";
  }
};

// 产品类目列表
const productionTypeList = ref([]);
async function getProductionTypeList() {
  let res = await request({
    url: "/qms/qmsproductiontype/getList",
    method: "post",
    data: {},
  }).finally(() => {
    loading.value = false;
  });
  productionTypeList.value = res.data;
}

const changeProduction = (e) => {
  if (e) {
    productionTypeList.value.forEach((item) => {
      if (item.id == e) {
        formData.productionTypeName = item.productionTypeName;
      }
    });
  } else {
    formData.productionTypeName = "";
  }
};

// 失效模式树列表
const failureModeList = ref([]);
async function getFailureMode() {
  let res = await request({
    url: "/qms/qmsfailuremode/getTree",
    method: "post",
    data: {},
  }).finally(() => {
    loading.value = false;
  });
  failureModeList.value = res.data;
}

const handleNodeClick = (e) => {
  if (e) {
    formData.failureModeContent = e.failureModeContent;
  } else {
    formData.failureModeContent = "";
  }
};
// 异常信息来源列表
const informationSourceList = ref([]);
async function getInformationSourceList() {
  let res = await request({
    url: "/qms/qmsinformationsource/getList",
    method: "post",
    data: {},
  }).finally(() => {
    loading.value = false;
  });
  informationSourceList.value = res.data;
}

const changInformationSource = (e) => {
  if (e) {
    informationSourceList.value.forEach((item) => {
      if (item.id == e) {
        formData.informationSourceContent = item.informationSourceContent;
      }
    });
  } else {
    formData.informationSourceContent = "";
  }
};
// 供应商列表
const supplyList = ref([]);
async function getSupplyList() {
  let res = await request({
    url: "mdm/mdmpartner/getListByFull",
    method: "post",
    data: {},
  }).finally(() => {
    loading.value = false;
  });
  supplyList.value = res.data;
}

const changSupplyList = (e) => {
  if (e) {
    supplyList.value.forEach((item) => {
      if (item.id == e) {
        formData.supplyName = item.partnerName;
        formData.supplyCode = item.partnerCode;
      }
    });
  } else {
    formData.supplyName = "";
    formData.supplyCode = "";
  }
};

const changIsInternal = (e) => {
  formData.supplyId = "";
  formData.supplyName = "";
  formData.supplyCode = "";
};

// 图片处理
function updateFormFiles(val: []) {
  formData.assetPhotos = val;
}
onMounted(() => {
  getMaterialProcess();
  getProductionTypeList();
  getFailureMode();
  getInformationSourceList();
  getSupplyList();
});
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
